//
//  YWApplyMaterialTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWApplyMaterialTableViewController.h"
#import "Masonry.h"
#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"

#import "YWSelectContactTableViewController.h"
#import "YWSelectMaterialTableViewController.h"
#import "YWSelectBuildingTableViewController.h"

#import "YWWriteNoteCell.h"
#import "YWSelectPersonTableViewCell.h"

#import "YWHandler.h"
#import "YWConst.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWMaterialManager.h"
#import "YWMaterialStock.h"

@interface YWApplyMaterialTableViewController ()<YWSelectPersonTableViewCellDelegate,YWContactVCSelectContactDelegate,YWSelectMaterialTableViewControllerDelegate,YWSelectBuildingTableViewControllerDelegate,YWWriteNoteCellDelegate>{
    NSString * noteString;
}
@property (nonatomic, strong) YWBuilding *building;
@property (nonatomic, strong) UIView * footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) NSMutableArray * receiveContacts;
@property (nonatomic, strong) NSMutableArray * sendContacts;
@property (nonatomic, strong) NSMutableArray * materialArray;
@property (nonatomic, assign) NSInteger currentSelectTag;

@end

@implementation YWApplyMaterialTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"物料申请";
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backToBeforeView:)];
    [self.tableView registerClass:[YWSelectPersonTableViewCell class] forCellReuseIdentifier:YWSelectPersonTableViewCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    self.tableView.tableFooterView = self.footView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSMutableArray *)receiveContacts{
    if (!_receiveContacts) {
        _receiveContacts = [NSMutableArray array];
    }
    return _receiveContacts;
}
- (NSMutableArray *)sendContacts{
    if (!_sendContacts) {
        _sendContacts = [NSMutableArray array];
    }
    return _sendContacts;
}
- (NSMutableArray *)materialArray{
    if (!_materialArray) {
        _materialArray = [NSMutableArray array];
    }
    return _materialArray;
}

-(YWBuilding *)building{
    if (!_building) {
        NSArray *allBuildings = [[NSArray alloc] initWithArray:[[YWBuildingManager shareManager] allBuilding]];
        _building = allBuildings.count>0 ? allBuildings[0] : nil;
    }
    return _building;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"YWApplyMaterialTableViewControllerCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        YWLoginUser * user = [YWLoginTool loginUser];
        cell.textLabel.text = user.userName;
        return cell;
    }else if(indexPath.section == 4){
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.textViewPlaceHolder = @"用途";
        cell.delegate = self;
        return cell;
    }else if(indexPath.section == 1){
        YWSelectPersonTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWSelectPersonTableViewCellIdentifier];
        cell.delegate = self;
        
        cell.btnTag = KReceiveAddBtnTag;
        cell.selectedContactsArray = self.receiveContacts;
        return cell;
    }
//    else if (indexPath.section == 2){
//        YWSelectPersonTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWSelectPersonTableViewCellIdentifier];
//        cell.delegate = self;
//        cell.btnTag = KSendAddBtnTag;
//        cell.selectedContactsArray = self.sendContacts;
//        return cell;
//    }
    else if (indexPath.section == 2){
        static NSString *identifier = @"YWApplyMaterialTableViewControllerCellSelectBuildingIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = self.building.buildingName;
        return cell;
    }
    else{
        YWSelectPersonTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWSelectPersonTableViewCellIdentifier];
        cell.delegate = self;
        cell.btnTag = KMaterialAddBtnTag;
        cell.materialsArray = self.materialArray;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        YWSelectBuildingTableViewController * selectBuilding = [[YWSelectBuildingTableViewController alloc] init];
        selectBuilding.delegate = self;
        selectBuilding.ownBuilding = self.building;
        [self.navigationController pushViewController:selectBuilding animated:YES];
    }
}

- (void)popSelectedBuilding:(YWBuilding *)building{
    self.building = building;
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
//     [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    self.materialArray = nil;
    [self.tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 4) {
        return 90;
    }else if (indexPath.section == 1){
        CGFloat selfSizeHeight = (self.receiveContacts.count/3+1)*(KNameLabelHeight+KcontentGap) + KcontentGap;
        return selfSizeHeight;
    }
//    else if (indexPath.section == 2){
//        CGFloat selfSizeHeight = (self.sendContacts.count/3+1)*(KNameLabelHeight+KcontentGap) + KcontentGap;
//        return selfSizeHeight;
//    }
    else if (indexPath.section == 3){
        CGFloat selfSizeHeight = (self.materialArray.count/3+1)*(KNameLabelHeight+KcontentGap) + KcontentGap;
        return selfSizeHeight;
    }else{
        return 44;
    }
}
#pragma mark - tableView section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWMaterialDetailTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2016;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, (SCREEN_WIDTH - 2 * 15)/2, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return @"申请人";
    }else if (section == 1){
        return @"接收人";
    }
//    else if(section == 2){
//        return @"抄送人";
//    }
    else if (section == 2){
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        return [NSString stringWithFormat:@"选择%@",buildingShowName];
    }else if(section == 3){
        return @"物料清单";
    }else{
        return @"用途";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickCommitButton:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

#pragma mark - delegate
- (void)jumpToselectPerson:(NSInteger)buttonTag{
    _currentSelectTag = buttonTag;
    switch (buttonTag) {
        case KReceiveAddBtnTag:{
            if (self.building.buildingId) {
                YWSelectContactTableViewController * selectContactVC = [[YWSelectContactTableViewController alloc] init];
                selectContactVC.delegate = self;
                selectContactVC.buildingId = self.building.buildingId;
                selectContactVC.isMultiSelect = YES;
                selectContactVC.ownContacts = self.receiveContacts;
                selectContactVC.titleName = @"选择接收人";
                [self.navigationController pushViewController:selectContactVC animated:YES];
            }else{
                NSString *buildingShowName = [YWLoginTool buildingShowName];
                [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"请先选择%@",buildingShowName]];
            }
        }
            break;
        case KMaterialAddBtnTag:{
            YWSelectMaterialTableViewController * selectMaterialVC = [[YWSelectMaterialTableViewController alloc] init];
            selectMaterialVC.ownMaterialArray = self.materialArray;
            selectMaterialVC.delegate = self;
            selectMaterialVC.building = self.building;
            [self.navigationController pushViewController:selectMaterialVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)selectMultipleContact:(NSArray*)contactArray{
    switch (_currentSelectTag) {
        case KReceiveAddBtnTag:{
            [self.receiveContacts removeAllObjects];
            [self.receiveContacts addObjectsFromArray:contactArray];
            NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:1];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:index.section] withRowAnimation:UITableViewRowAnimationFade];
        }
            break;
//        case KSendAddBtnTag:{
//            [self.sendContacts removeAllObjects];
//            [self.sendContacts addObjectsFromArray:contactArray];
//            NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:2];
//            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:index.section] withRowAnimation:UITableViewRowAnimationFade];
//        }
//            break;
        case KMaterialAddBtnTag:{
            [self.materialArray removeAllObjects];
            [self.materialArray addObjectsFromArray:contactArray];
            NSIndexPath * index = [NSIndexPath indexPathForRow:0 inSection:3];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:index.section] withRowAnimation:UITableViewRowAnimationFade];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - YWSelectMaterialTableViewControllerDelegate
- (void)popSelectMaterials:(NSMutableArray *)materialViewModelArray{
    //返回选择的物料(materialStock)
    self.materialArray = nil;
    self.materialArray = materialViewModelArray;
    [self.tableView reloadData];
}

- (void)cancelButtonEvent:(NSInteger)buttonTag{
    [self.tableView reloadData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)clickCommitButton:(UIButton *)sender{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提交申请" message:@"您确定提交申请吗？" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self submitCreateMaterialApply];
    }]];
}

- (void)passNote:(NSString*)note
{
    noteString = note;
}

- (void)submitCreateMaterialApply
{
    if (self.receiveContacts.count==0) {
        [YWCommonTool showTextHUDWithContent:@"请选择接收人"];
        return;
    }
    if (self.materialArray.count==0) {
        [YWCommonTool showTextHUDWithContent:@"请选择物料"];
        return;
    }
    if ([YWCommonTool isContainsEmoji:noteString]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    //创建物料申请单
    [self.view endEditing:YES];
    [self.HUD show:YES];
    [[YWMaterialManager shareManager] createMaterialApplyWithBuildingId:self.building.buildingId Receivers:self.receiveContacts CarbonCopy:self.sendContacts Note:noteString MaterialInfo:self.materialArray WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:@"提交物料申请成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostCommitApplyMaterialSuccessNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)backToBeforeView:(id)sender{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"退出申请" message:@"您确定退出此次申请吗？" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
}

@end
